/**
**/
jsx3.lang.Class.defineClass(
        "tibco.admin.deployment.sa.uploadSA.UploadSA",
        jsx3.lang.Object,
        null,
        function(plugin) {
            plugin.form = null;
            plugin.serviceAssemblyName = "";
            plugin.serviceAssemblyEntityeID = "";
            plugin.environment = "";
            plugin.environmentEntityID = "";
            plugin.archivePath = "";
            plugin.importSharedResourceConfiguration = true;
            plugin.isIE = true;

            plugin.nameEnabled = true;

            plugin.subscribeAll = function() {
                tibco.admin.PubSub.subscribe("tibco.deployment.serviceAssemblyList.ServiceAssemblyList.ONNEWSERVICEASSEMBLY", plugin.setEnvironmentParameters)
            }

            plugin.unsubscribeAll = function() {
                tibco.admin.PubSub.unsubscribeAll("tibco.deployment.serviceAssemblyList.ServiceAssemblyList.ONNEWSERVICEASSEMBLY")
            }

            plugin.setEnvironmentParameters = function(objEvent) {
                plugin.environment = objEvent.environment;
                plugin.environmentEntityID = objEvent.evnEntityID;
            }

            plugin.setSANameBySADetail = function(enabled, entityID, envEntityID, name) {
                plugin.serviceAssemblyEntityeID = entityID;
				plugin.environmentEntityID = envEntityID;
                var o = plugin.block.getDescendantOfName("txtInputSAName_401");
                o.setValue(name);
                o.setEnabled(enabled);
                o.repaint();

				var chkImportSRDef = plugin.block.getDescendantOfName("chkImportSharedResourceConfiguration_401");
				chkImportSRDef.setVisibility(jsx3.gui.Block.VISIBILITYHIDDEN);
				chkImportSRDef.repaint();

                plugin.nameEnabled = enabled;
            }


            /**
             * Initializes the Add service assembly based on the browser IE or FF
             */
            plugin.initializeBrowser = function() {
                if (document.getElementById && !document.all) {
                    // user is using NS6+ or Firefox
                    plugin.isIE = false
                    // set blocks
                    plugin.block.getDescendantOfName("blkArchiveFileMZ_401").setDisplay(jsx3.gui.Block.DISPLAYBLOCK, true);
                    plugin.block.getDescendantOfName("blkArchiveFile_401").setDisplay(jsx3.gui.Block.DISPLAYNONE, true);

                    setTimeout(function() {
                        plugin.initIFrame()
                    }, 100)

                } else {
                    plugin.block.getDescendantOfName("blkArchiveFileMZ_401").setDisplay(jsx3.gui.Block.DISPLAYNONE, true);
                    plugin.block.getDescendantOfName("blkArchiveFile_401").setDisplay(jsx3.gui.Block.DISPLAYBLOCK, true);
                }

            }

            /**
             * If FF then create an iframe with a form element
             */
            plugin.initIFrame = function() {

                // var strDiv =  "<div id='spanMoz2354AX' width='250' height= '50'  top='0' left='0' > <iframe id='iFrameMoz2354AX'  width='240'  height='50' frameborder='no' scrolling='no'  ></iframe></div>"
                var strDiv = "<div id='spanMoz2354AX' width='250' height= '33'  top='0' left='0'> <iframe id='iFrameMoz2354AX'  width='240'  height='33' frameborder='no' scrolling='no'  ></iframe></div>"

                plugin.block.getDescendantOfName('blkRootAddServiceAssemblyMZ_401').setText(strDiv, true);
                plugin.block.getDescendantOfName("btnAddServiceAssembly_401").setEnabled(jsx3.gui.Form.STATEENABLED, true);
                var strAction = tibco.admin.util.ServiceHelper.getAssemblyLoadPath()
                var theForm = '<form id="formMoz2354AX"  enctype="multipart/form-data"  method="post" action="' + strAction + '" ><input id="fileMoz2354AX" type="file" name="upfile" style="position:absolute;top:0;left:0" ></input></form>';
                // var docHTML = '<html><script type="text/javascript"  language="JavaScript" src="scripts/javascripts/mainfunction.js" ><!-- //--></script><head></head><body>' + theForm + '</body></html>';
                var docHTML = '<html><head></head><body>' + theForm + '</body></html>';

                plugin._span = document.getElementById("spanMoz2354AX");
                plugin._iframe = document.getElementById("iFrameMoz2354AX");
                plugin._iframe.contentDocument.open();
                plugin._iframe.contentDocument.write(docHTML);
                setTimeout(function() {
                    plugin.form = plugin._iframe.contentDocument.getElementById("formMoz2354AX")
                    plugin._iframe.contentDocument.close();
                }, 100)

            };

            /*
            * Browsing for a file.
            */
            plugin.doBrowse = function() {
                jsx3.require('jsx3.net.Form');
                if (plugin.isIE) {
                    // Get the URL to post to
                    var strTestURL = tibco.admin.util.ServiceHelper.getAssemblyLoadPath()
                    if (plugin.form)
                        plugin.doReset();
                    //get handle to the on-screen textbox that will show the user the name/path of the file they chose to upload
                    var objText = plugin.block.getDescendantOfName("txtArchiveFile_401");
                    //check if the form has been created (it gets created when the file upload button is clicked)
                    if (!plugin.form) {
                        // plugin.form = new jsx3.net.Form(jsx3.net.Form.METHOD_POST, strTestURL, true);
                        plugin.form = jsx3.net.Form.newFromFragment('<form id="deploymentuploadform" enctype="multipart/form-data"  method="post" action="' + strTestURL + '"></form>');
                        //plugin.form.setMultipart(true)
                        //add a file upload field. Give it an ID for later use (just use the name of the jsx textbox for now)
                        plugin.form.addFileUploadField(objText.getName());

                        plugin.form.subscribe(jsx3.net.Form.EVENT_FILE_SELECTED, function(objEvent) {
                            objText.setValue(objEvent.value.substr(objEvent.value.lastIndexOf("\\") + 1));
                            plugin.block.getDescendantOfName("btnAddServiceAssembly_401").setEnabled(jsx3.gui.Form.STATEENABLED, true);
                        });
                    }
                    plugin.form.promptForFile(objText.getName());
                }
            }

            /**
             * submit to save the archive file (IE specific)
             */
            plugin.doSubmit = function(button) {
                if (!plugin.validateAddServiceAssembly()) {
                    return;
                }

				plugin.importSharedResourceConfiguration =
						plugin.block.getDescendantOfName("chkImportSharedResourceConfiguration_401").getChecked() == jsx3.gui.CheckBox.CHECKED;
                plugin.block.getDescendantOfName("chkImportSharedResourceConfiguration_401").setEnabled(jsx3.gui.Form.STATEDISABLED, true);
                plugin.block.getDescendantOfName("btnAddServiceAssembly_401").setEnabled(jsx3.gui.Form.STATEDISABLED, true);
                plugin.block.getDescendantOfName("btnCancelServiceAssembly_401").setEnabled(jsx3.gui.Form.STATEDISABLED, true);
                plugin.block.getDescendantOfName('blkUploadMessage_401').setText(tibco.admin.Main.getServer().getDynamicProperty("@msgUploading_401"), true);

                if (plugin.isIE) {
                    if (!plugin.form) {
                        tibco.admin.util.Log.DEPLOYMENT.trace("form is null.");
                        plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgFormIsNull_401"), true);
                        plugin.doReset();
                        return;
                    }

                    var nameField = plugin.block.getDescendantOfName('txtInputSAName_401');

                    plugin.serviceAssemblyName = nameField.getValue();
                    var pathField = plugin.block.getDescendantOfName('txtArchiveFile_401');
                    plugin.archivePath = pathField.getValue();

                    plugin.form.setField("assembly", plugin.serviceAssemblyName);
                    plugin.form.setField("environment", plugin.environment);
                    nameField.setEnabled(jsx3.gui.Form.STATEDISABLED, true);
                    plugin.block.getDescendantOfName("btnBrowseSAArchive_401").setEnabled(jsx3.gui.Form.STATEDISABLED, true);
                    plugin.form.subscribe(jsx3.HttpForm.EVENT_ON_RESPONSE, function(objEvent) {
                        try {
                            var responsexml =  plugin.form.getResponseXML()
                            if(responsexml.hasError()){
                                if(plugin._sessionExpired())
                                return;
                            }
                            plugin.doProfile((new jsx3.xml.Document()).loadXML(responsexml));
                        }
                        catch(e) {
                            if(plugin._sessionExpired())
                              return;
                            plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgUploadInvalid_401", plugin.serviceAssemblyName)+"\nDetail:"+e, true);
                            plugin.doReset();
                        }

                    });
                    plugin.form.subscribe(jsx3.HttpForm.EVENT_ON_TIMEOUT, function(objEvent) {
                        if(plugin._sessionExpired())
                           return;
                        plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgUploadTimeout_401", plugin.serviceAssemblyName), true);
                        plugin.doReset();
                    });
                    plugin.form.subscribe(jsx3.HttpForm.EVENT_ON_ERROR, function(objEvent) {
                        if(plugin._sessionExpired())
                           return;
                        plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgUploadError_401", plugin.serviceAssemblyName), true);
                        plugin.doReset();
                    });
                    plugin.form.setMultipart(true);
                    plugin.form.send(500, 60000);
                }
                else {
                    plugin.doSubmitMZ(button);
                }
            }

            /**
             * submit to save the archive file (FF specific)
             */
            plugin.doSubmitMZ = function(button) {
                if (!plugin.form) {
                    plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgFormIsNull_401"), true);
                    plugin.form = null
                    return;
                }

                var nameField = plugin.block.getDescendantOfName('txtInputSAName_401');
                plugin.serviceAssemblyName = nameField.getValue();

                plugin.setField("assembly", plugin.serviceAssemblyName);
                plugin.setField("environment", plugin.environment);
                nameField.setEnabled(jsx3.gui.Form.STATEDISABLED, true);

                plugin.form.encoding = 'multipart/form-data'

                plugin.send()
            }


            plugin.send = function(intPollInterval, intTimeout) {
                if (intPollInterval == null) intPollInterval = 10;
                if (intTimeout == null) intTimeout = 30000;

                plugin._iframe.onload = function() {
                    plugin.onIFrameLoad();
                }

                try {
                    plugin.form.submit();
                } catch (e) {
                        if(plugin._sessionExpired())
                           return;
                    tibco.admin.util.Log.DEPLOYMENT.trace("Error loading service asembly")
                    plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgUploadError_401", plugin.serviceAssemblyName), true);
                    plugin.doReset();
                    plugin.initIFrame()
                    return;
                }

                plugin._sessionIntervalid = window.setTimeout(function() {
                    if(plugin._sessionExpired())
                           return;
                }, 4000 );

                plugin._intervalId = window.setTimeout(function() {
                    plugin.onIFrameTimeout();
                }, intPollInterval * intTimeout);
            };

            /* @jsxobf-clobber */
            plugin.onIFrameLoad = function() {
                plugin._iframe.onload = null;
                if ( plugin._sessionIntervalid ) {
                    window.clearTimeout(plugin._sessionIntervalid);
                    plugin._sessionIntervalid = null;
                }
                if (plugin._intervalId) {
                    window.clearTimeout(plugin._intervalId);
                    plugin._intervalId = null;
                }

                try {
                    var a = " " + plugin._iframe.contentDocument.childNodes[0].innerHTML;
                } catch (e) {
                    if(plugin._sessionExpired())
                           return;
                    plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgUploadError_401", plugin.serviceAssemblyName), true);
                    plugin.doReset();
                    plugin.initIFrame()
                    return;
                }
                var s = plugin.getResponseXML();
                plugin.initIFrame();
                plugin.block.getDescendantOfName("btnAddServiceAssembly_401").setEnabled(jsx3.gui.Form.STATEDISABLED, true);
                if (s.hasError()) {
                    if (plugin._sessionExpired())
                        return;
                }
                plugin.doProfile(s);

            };


            /* @jsxobf-clobber */
            plugin.onIFrameTimeout = function() {
                if(plugin._sessionExpired())
                           return;
                plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgUploadError_401", plugin.serviceAssemblyName), true);
                plugin.doReset()
                plugin.initIFrame()

            };


            plugin.getResponseXML = function() {
                plugin._iframe = document.getElementById("iFrameMoz2354AX");
                var dcmt = plugin._iframe.contentDocument;
                if (dcmt instanceof XMLDocument) {
                    var x = (new XMLSerializer()).serializeToString(dcmt);
                    return new jsx3.xml.Document().loadXML(x);
                }
                else if (dcmt instanceof HTMLDocument) {
                    var x = dcmt.childNodes[0].innerHTML;
                    return new jsx3.xml.Document().loadXML(x);
                } else {
                    tibco.admin.util.Log.DEPLOYMENT.warn("Unsupported document type: " + dcmt);
                    return new jsx3.xml.Document().loadXML("<html/>");
                }
            };


            plugin.setField = function(name, value) {
                var newInput = document.createElement('input');
                newInput.setAttribute("type", "hidden");
                newInput.setAttribute("name", name);
                newInput.setAttribute("value", value);
                plugin.form.appendChild(newInput);
            }


            plugin.validateAddServiceAssembly = function() {
                // Validate  service assembly name
                var nameField = plugin.block.getDescendantOfName('txtInputSAName_401');
                if(nameField.getValue().replace(/^\s|\s$/gim, "")==""){
                    plugin.actionOnValidation(nameField, false, tibco.admin.Main.getServer().getDynamicProperty("@msgValideWhitespaceErrorMessage_401", "'Name'"));
                    tibco.admin.Main.alert(
                            tibco.admin.Main.getServer().getDynamicProperty("@msgEmptyNameTitle_401"),
                            tibco.admin.Main.getServer().getDynamicProperty("@msgEmptyNameMessage_401")
                            )
                    return false;
                }
                else{
                    plugin.actionOnValidation(nameField, true, "");
                }
                if (plugin.isIE) {
                    var pathField = plugin.block.getDescendantOfName('txtArchiveFile_401');
                    if(pathField.getValue().replace(/^\s|\s$/gim, "")==""){
                        plugin.actionOnValidation(pathField, false, tibco.admin.Main.getServer().getDynamicProperty("@msgSelectFileToUploadMessage_401", "'Archive File'"));
                        tibco.admin.Main.alert(
                                tibco.admin.Main.getServer().getDynamicProperty("@msgSelectFileToUploadTitle_401"),
                                tibco.admin.Main.getServer().getDynamicProperty("@msgSelectFileToUploadMessage_401")
                                )
                        return false;
                    }
                    else{
                        plugin.actionOnValidation(pathField, true, "");
                    }
                }
                return true;
            }

            plugin.actionOnValidation = function(objText, passed, strValue, message) {
                try {
                    if (!passed) {
                        objText.setBackgroundColor("yellow", true);
                        plugin.showError(message)
                    }
                    else {
                        // Set the trimed value for node
                        //objText.setValue(strValue, true)
                        objText.setBackgroundColor("#FFFFFF", true);
                        plugin.showError(message)
                    }
                }
                catch(e) {

                }
            };

            /**
             *
             */
            plugin.doProfile = function(objXML) {
                try {
                    var successOrFailure = objXML.getRootNode().selectSingleNode("//status").getValue();
                    if (successOrFailure == "SUCCESS") {
                        plugin.archivePath = objXML.selectSingleNode("//path").getValue();
                        plugin.archivePath = plugin.archivePath.replace(/^\s*|\s*$/g, "");

                        plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgUploadedWaiting_401", plugin.serviceAssemblyName));
                        try {
                            if (plugin.serviceAssemblyEntityeID == "") {   // add a new service assembly
                                plugin.calladdServiceAssembly();
                            }
                            else {   // update the existing service assembly
                                plugin.callupdateServiceAssembly();
                            }
                        }
                        catch(e) {
                            plugin.doReset();
                            plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("msgRetrieveFailed_401", plugin.serviceAssemblyName));
                            if(!plugin.isIE) {
                                plugin.initIFrame()
                            }
                        }
                    }
                    else {
                        var errorMessage = objXML.selectSingleNode("//error").getValue();
                        plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgUploadFailed_401", errorMessage), true);
                        plugin.serviceAssemblyName = "";
                        plugin.doReset();
                        if(!plugin.isIE) {
                            plugin.initIFrame()
                        }
                    }
                }
                catch(e) {
                    plugin.showError(tibco.admin.Main.getServer().getDynamicProperty("@msgUploadError_401", plugin.serviceAssemblyName), true);
                    plugin.doReset();
                    if (!plugin.isIE) {
                        plugin.initIFrame()
                    }

                }
            }

            plugin.doReset = function() {
                if (plugin.isIE && plugin.form)
                    plugin.form.destroy();

                plugin.form = null;
                plugin.block.getDescendantOfName("txtInputSAName_401").setEnabled(plugin.nameEnabled ? jsx3.gui.Form.STATEENABLED : jsx3.gui.Form.STATEDISABLED, true);
                plugin.block.getDescendantOfName("txtArchiveFile_401").setValue("");
                plugin.block.getDescendantOfName("btnBrowseSAArchive_401").setEnabled(jsx3.gui.Form.STATEENABLED, true);
                plugin.block.getDescendantOfName("chkImportSharedResourceConfiguration_401").setEnabled(jsx3.gui.Form.STATEENABLED, true);
                plugin.block.getDescendantOfName("btnAddServiceAssembly_401").setEnabled(jsx3.gui.Form.STATEDISABLED, true);
                plugin.block.getDescendantOfName("btnCancelServiceAssembly_401").setEnabled(jsx3.gui.Form.STATEENABLED, true);

                if (!plugin.isIE) {
                    // to do:  && plugin._iframe.contentDocument.getElementById("fileMoz2354AX")
                    // plugin._iframe.contentDocument.getElementById("fileMoz2354AX").setAttribute("disabled","false");
                    plugin.block.getDescendantOfName("btnAddServiceAssembly_401").setEnabled(jsx3.gui.Form.STATEENABLED, true);

                }
            }

            plugin.showError = function(msg) {
                plugin.block.getDescendantOfName('blkUploadMessage_401').setText(msg, true);
            }


            plugin.calladdServiceAssembly = function() {
                var objService = tibco.admin.Main.loadService("tibco.admin", "tibco/admin/deployment/sa/uploadSA/rules/addServiceAssembly.xml", "addServiceAssembly");

                objService.subscribe(jsx3.net.Service.ON_SUCCESS, plugin.onaddServiceAssemblySuccess);
                objService.subscribe(jsx3.net.Service.ON_ERROR, plugin.onaddServiceAssemblyError);
                objService.subscribe(jsx3.net.Service.ON_INVALID, plugin.onaddServiceAssemblyInvalid);
                //objService.subscribe(jsx3.net.Service.ON_TIMEOUT, function(){alert("timeout")});

                objService.environment = plugin.environment;
                objService.environmentEntityID = plugin.environmentEntityID;
                objService.archivePath = plugin.archivePath;
                objService.serviceAssemblyName = plugin.serviceAssemblyName;
                objService.importSharedResourceConfiguration = plugin.importSharedResourceConfiguration;

                objService.setEndpointURL(tibco.admin.util.ServiceHelper.getDeploymentEndpointURL())

                objService.doCall();

            };

            plugin.onaddServiceAssemblySuccess = function(objEvent) {
                // Send a message to refresh the service assembly list
                var obj = {};
                obj.subject = tibco.admin.deployment.saList.EventID.SERVICEASSEMBLY_ADD_SUCCESSFUL;
                obj.name = plugin.block.getDescendantOfName("txtInputSAName_401").getValue();
                obj.archiveFile = plugin.block.getDescendantOfName("txtArchiveFile_401").getValue();

                plugin.block.doClose();
                tibco.admin.PubSub.publish(obj);

            };

            plugin.onaddServiceAssemblyError = function(objEvent) {
                plugin.doReset();
                if (!plugin.isIE) {
                    plugin.initIFrame()
                }
            };

            plugin.onaddServiceAssemblyInvalid = function(objEvent) {
                plugin.doReset();
                if (!plugin.isIE) {
                    plugin.initIFrame()
                }
            };

            plugin.destroyDialog = function(dialog) {
                dialog.doClose();
            };


            //call this method to begin the service call (eg.service.callupdateServiceAssembly();)
            plugin.callupdateServiceAssembly = function() {
                var objService = tibco.admin.Main.loadService("tibco.admin", "tibco/admin/deployment/sa/uploadSA/rules/updateServiceAssembly.xml", "updateServiceAssembly");

                //subscribe and call
                objService.subscribe(jsx3.net.Service.ON_SUCCESS, plugin.onupdateServiceAssemblySuccess);
                objService.subscribe(jsx3.net.Service.ON_ERROR, plugin.onupdateServiceAssemblyError);
                objService.subscribe(jsx3.net.Service.ON_INVALID, plugin.onupdateServiceAssemblyInvalid);

                objService.environment = plugin.environment;
                objService.environmentEntityID = plugin.environmentEntityID;
                objService.serviceAssemblyEntityeID = plugin.serviceAssemblyEntityeID;
                objService.archivePath = plugin.archivePath;
                objService.serviceAssemblyName = plugin.serviceAssemblyName;
                objService.importSharedResourceConfiguration = plugin.importSharedResourceConfiguration;

                objService.setEndpointURL(tibco.admin.util.ServiceHelper.getDeploymentEndpointURL());

                objService.doCall();
            };

            plugin.onupdateServiceAssemblySuccess = function(objEvent) {
                var obj = {};
                obj.subject = tibco.admin.deployment.saList.EventID.SERVICEASSEMBLY_UPDATE_SUCCESSFUL;
                obj.name = plugin.block.getDescendantOfName("txtInputSAName_401").getValue();
                obj.archiveFile = plugin.block.getDescendantOfName("txtArchiveFile_401").getValue();
                plugin.serviceAssemblyEntityeID = "";
                plugin.block.doClose();
            };

            plugin.doCancel = function() {
                plugin.serviceAssemblyEntityeID = "";
            };

            plugin.onupdateServiceAssemblyError = function(objEvent) {
                plugin.doReset();
                if(!plugin.isIE) {
                    plugin.initIFrame()
                }

            };

            plugin.onupdateServiceAssemblyInvalid = function(objEvent) {
                plugin.doReset();
                if(!plugin.isIE) {
                    plugin.initIFrame()
                }
            };

            plugin.onAfterDeserialize = function(objJSX) {
                plugin.block = objJSX;
                try {
                    plugin.initializeBrowser()
                    plugin.subscribeAll();
                }
                catch(e){
                      tibco.admin.Main.alert(tibco.admin.Main.getServer().getDynamicProperty("@msgErrorTitle_401"), e)
                }

            }


            plugin._sessionExpired = function() {
                if (tibco.admin.Main.getServer().getEnv("MODE")) {
                    if (tibco.admin.util.ServiceHelper.sessionExpired()) {
                        tibco.admin.util.Log.SERVICE.warn("tibco.admin.deployment.sa.uploadSA.UploadSA#_sessionExpired: session is expired");
                        tibco.admin.util.ServiceHelper.redirectToLoginPage();
                        return true;
                    }
                }
                return false;
            }

        }
        )
